package com.hfy.kandian.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hfy.kandian.entity.Follow;
import com.hfy.kandian.entity.User;
import com.hfy.kandian.mapper.FollowMapper;
import com.hfy.kandian.mapper.UserMapper;
import com.hfy.kandian.service.FollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author HAN XIAOYANG
 * @since 2020-12-30
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements FollowService {

    @Autowired
    public FollowMapper followMapper;

    @Autowired
    public UserMapper userMapper;

    //TODO:主从复制实现？
    @Override
    public int doFollow(int thisId, int targetId) {
        List<Integer> list = new ArrayList<>();
        //不存在则插入，存在则更新
        Follow res = followMapper.selectOne(new LambdaQueryWrapper<Follow>().eq(Follow::getTargetId,targetId));
        if(ObjectUtils.isEmpty(res)){
            list.add(thisId);
            return followMapper.insert(new Follow().setTargetId(targetId).setUserIds(JSON.toJSONString(list)));
        }else{
            list = JSONArray.parseArray(res.getUserIds(), Integer.class);
            list.add(thisId);
            res.setUserIds(JSON.toJSONString(list));
            return 1;
        }

    }

    @Override
    public int unFollow(int thisId, int targetId) {
        Follow res = followMapper.selectOne(new LambdaQueryWrapper<Follow>().eq(Follow::getTargetId,targetId));
        List<Integer> list = JSONArray.parseArray(res.getUserIds(),Integer.class);
        list.remove(thisId);
        return followMapper.updateById(res);
    }

    @Override
    public List<User> showFollower(int thisId) {
        List<Integer> list = JSONArray.parseArray(followMapper.selectById(thisId).getUserIds(), Integer.class);
        return userMapper.selectBatchIds(list);
    }

    @Override
    public List<User> showTargets(int thisId) {
        //List<User> list = ;
        return null;
    }


}
